package com.xncoding.wechat.Controller;


import com.xncoding.wechat.dto.BankCardElement;
import com.xncoding.wechat.dto.FsBankCardRedirectInput;
import com.xncoding.wechat.dto.FsBankCardRedirectOutput;
import com.xncoding.wechat.service.BankCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/api/bankcard")
@Validated
@CrossOrigin(origins = "*")
public class BankCardRedirectController {

    @Autowired
    private BankCardService bankCardService;

    /**
     * 跳转银行选卡页面主接口
     */
    @PostMapping("/redirect")
    public FsBankCardRedirectOutput redirectToBankCardPage(@Valid @RequestBody FsBankCardRedirectInput request) {
        try {
            String redirectUrl = bankCardService.generateRedirectUrl(request);
            return FsBankCardRedirectOutput.success(redirectUrl);
        } catch (Exception e) {
            return FsBankCardRedirectOutput.error("跳转失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public FsBankCardRedirectOutput healthCheck() {
        return FsBankCardRedirectOutput.success("服务正常运行");
    }

    /**
     * 测试接口：生成加密银行要素块
     */
    @PostMapping("/test/encrypt")
    public FsBankCardRedirectOutput testEncrypt(@RequestParam Integer creType,
                                                @RequestParam String creId,
                                                @RequestParam String trueName) {
        try {
            BankCardElement element = new BankCardElement();
            element.setCreType(creType);
            element.setCreId(creId);
            element.setTrueName(trueName);

            String encrypted = bankCardService.generateBankElementEncrypted(element);
            return FsBankCardRedirectOutput.success(encrypted);
        } catch (Exception e) {
            return FsBankCardRedirectOutput.error("加密失败: " + e.getMessage());
        }
    }

    /**
     * 生成跳转银行绑卡页面参数
     */
    @PostMapping("/generate")
    public ResponseEntity<?> generateBindCardUrl(
            @RequestParam String openId,
            @RequestParam String sessionId,
            @RequestParam String[] cardTails,
            @RequestParam Integer creType,
            @RequestParam String creId,
            @RequestParam String trueName) {

        try {
            // 1. 准备银行要素
            BankCardElement bankElement = new BankCardElement(creType, creId, trueName);

            // 2. 加密银行要素
            String encBankElem = bankCardService.encryptBankElement(bankElement);

            // 3. 编码银行卡尾号
            String encodedBindTail = bankCardService.encodeBindTail(cardTails);

            // 4. 构建请求参数
            FsBankCardRedirectInput request = new FsBankCardRedirectInput();
            request.setSessionid(sessionId);
            request.setOpenid(openId);
            request.setBindTail(encodedBindTail);
            request.setEncBankelem(encBankElem);

            // 5. 生成跳转URL（这里返回参数，前端自己拼接URL）
            Map<String, Object> result = new HashMap<>();
            result.put("appid", request.getAppid());
            result.put("bind_tail", request.getBindTail());
            result.put("enc_bankelem", request.getEncBankelem());
            result.put("noncestr", request.getNoncestr());
            result.put("openid", request.getOpenid());
            result.put("sessionid", request.getSessionid());
            result.put("timestamp", request.getTimestamp());
            result.put("signtype", request.getSigntype());
            result.put("paysign", request.getPaysign());
            result.put("redirect_url", "/pages/wxpay_bindcard/index.html");

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body("生成绑卡参数失败");
        }
    }

    /**
     * 银行回调处理
     */
    @PostMapping("/callback")
    public ResponseEntity<?> bankCallback(@RequestBody Map<String, Object> callbackData) {
        try {
            // 验证签名
            boolean isValid = bankCardService.verifyBankResponse(
                    (String) callbackData.get("signature"),
                    (Map<String, String>) callbackData.get("params"));

            if (!isValid) {
                return ResponseEntity.badRequest().body( "签名验证失败");
            }

            // 处理绑卡结果
            String resultCode = (String) callbackData.get("result_code");
            String bindId = (String) callbackData.get("bind_id");
            String cardNo = (String) callbackData.get("card_no");

            Map<String, Object> response = new HashMap<>();
            if ("SUCCESS".equals(resultCode)) {
                response.put("code", 0);
                response.put("message", "绑卡成功");
                response.put("bind_id", bindId);
                response.put("card_no", cardNo);
            } else {
                response.put("code", -1);
                response.put("message", "绑卡失败");
                response.put("error_msg", callbackData.get("error_msg"));
            }

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body("hjj");
        }
    }

}